package com.hjx.movie.common.utils;

import com.hjx.movie.common.utils.exceptions.CustomException;
import lombok.Builder;
import lombok.Data;

import java.io.Serializable;

/**
 * <p>Title:</p>
 * <p>Description:</p>
 *
 * @author hjx
 * @date 2020/12/30 - 16:32
 */
@Data
@Builder
public class Result implements Serializable {
    private  boolean result;
    private  int code;
    private  String message;
    private  Object data;


    private Result() {

    }

    private Result(boolean result, int code, String message, Object data) {
        this.result = result;
        this.code = code;
        this.message = message;
        this.data = data;
    }

    //请求出现异常时的响应数据封装
    public static Result error(CustomException e) {
        Result resultBean = new Result();
        resultBean.setResult(false);
        resultBean.setCode(e.getCode());
        if(e.getCode() == ResultType.USER_INPUT_ERROR.getCode()){
            resultBean.setMessage(e.getMessage());
        }else if(e.getCode() == ResultType.SYSTEM_ERROR.getCode()){
            resultBean.setMessage(e.getMessage() + ",请将该异常信息发送给管理员!");
        }else{
            resultBean.setMessage("系统出现未知异常，请联系管理员!");
        }
        //TODO 这里最好将异常信息持久化
        return resultBean;
    }

    //请求出现异常时的响应数据封装
    public static Result error(ResultType resultType, String errorMessage) {
        return new Result(resultType.isResult(),
                resultType.getCode(),
                errorMessage,null);
    }
    //请求出现异常时的响应数据封装
    public static Result error(ResultType resultType) {
        return new Result(resultType.isResult(),
                resultType.getCode(),
                resultType.getMessage(), null);
    }
    //请求处理成功时的数据响应
    public static Result success() {
        return new Result(ResultType.SUCCESS.isResult(),
                ResultType.SUCCESS.getCode(),
                ResultType.SUCCESS.getMessage(), null);
    }

    //请求处理成功，并响应结果数据
    public static Result success(Object data) {
        return new Result(ResultType.SUCCESS.isResult(),
                ResultType.SUCCESS.getCode(),
                ResultType.SUCCESS.getMessage(), data);
    }

//    public static void main(String[] args) {
//        int a = 0;
//        for (int b=1;b<=100;b++){
//            a+=b;
//        }
//        System.out.println(a);
//    }

}
